<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

<div>广播：<span id="broadcast"></span></div>

<hr>

<div id="title">客户端</div>

<div id="conn"></div>

<hr>

聊天：
<div id="chat">



</div>

<hr>

<div>
    <p>// 发送格式：</p>
    <p>// {"to":"sId","content":"content"}</p>
</div>

<hr>

<div><textarea id="toSend" style="width: 300px; height: 100px;"></textarea></div>

<div><a href="#" id="send">发送</a></div>

<script>
    var socket;
    if(typeof(WebSocket) === "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else {
        console.log("您的浏览器支持WebSocket");

        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket("ws://localhost:8080/websocket");
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            var data = msg.data;
            console.log(data);
            var jsonObj = JSON.parse(data);
            var lab = jsonObj.label;
            console.log(lab);
            switch (lab) {
                case 0:
                    var conn = jsonObj.data;
                    $('#conn').html(conn);
                    break;
                case 1:
                    var broadcast = jsonObj.data;
                    $('#broadcast').html(broadcast);
                    break;
                case 2:
                    var from = jsonObj.data.from;
                    var content = jsonObj.data.content;

                    var news = '<p> <b>来自：</b>' + from + ' / <b>内容:</b>' + content + '</p>';
                    $('#chat').append(news);
                    break;
                default:
                    alert('this is what...');
                    break;
            }
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
        }
        $(window).unload(function(){
            socket.close();
        });

        // 发送消息
         $("#send").click(function() {
             socket.send($('#toSend').val());
         });

         // 关闭socket
         $("#btnClose").click(function() {
             socket.close();
         });
    }
</script>

</body>
</html>